package io;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import config.Config;
import crono.Cronometro;

public class FileNetSenderIO {
	public static void main(String[] args) throws IOException {
		Cronometro timer = new Cronometro();
		timer.start();

		boolean done = false;

		System.out.printf("Attemping to connect to host %s on port %d.\n",
				Config.NET_SERVER_IP, Config.NET_SERVER_PORT);

		try (Socket clientSocket = new Socket(Config.NET_SERVER_IP,
				Config.NET_SERVER_PORT, InetAddress.getByName(Config.NET_CLIENT_IP),
				Config.NET_CLIENT_PORT);
				OutputStream socketOut = clientSocket.getOutputStream();
				InputStream socketIn = clientSocket.getInputStream();
				DataInputStream fileIn = new DataInputStream(
						new FileInputStream(new File(Config.INPUT_FILE)));) {

			byte[] buf = new byte[Config.NET_BUF_SIZE];
			int size = Integer.MAX_VALUE;
			while (size > 0) {
				size = fileIn.read(buf);
				if (size > 0) {
					socketOut.write(buf, 0, size);
				}
			}

			System.out.println("Data has been sent. Waiting for ACK.");
			int ack = socketIn.read();
			if (ack == Config.TX_ACK_BYTE) {
				System.out.println("ACK received. TX verified.");
				done = true;
			} else {
				System.out.println("Unknown ACK received. TX NOT verified.");
			}
		} catch (UnknownHostException e) {
			System.err.printf("Don't know about host %s.\n",
					Config.NET_SERVER_IP);
		} catch (IOException e) {
			System.out.println("I/O Exception. Details: " + e);
		}

		if (done) {
			timer.stop();
			timer.print("IO. Copy file over network");
		}
	}
}